#ifndef LGE_THREADPOOL_H
#define LGE_THREADPOOL_H

#include <core/lge_thread.h>
#include <vector>

class ThreadPool
{
	/**
	  * \brief Keep a list of all threads in the pool
	  */
	std::vector<Thread*> mThreads;

public:
	/**
	  * \brief Create a new thread pool
	  */
	ThreadPool()
	{
		// Reserve memory to store all the threads. The most probable case is
		// to create a thread pool of size processor count, so reserve memory
		// in that way.
		mThreads.reserve(processorCount());
	}

	/**
	  * \brief Add a thread to the thread pool
	  */
	bool addThread(const ThreadFunction & function)
	{
		Thread * newThread = new Thread(function, false);
		if (!newThread)
			return false;
		mThreads.push_back(newThread);
		return true;
	}

	/**
	  * \brief Start all threads in that pool
	  */
	bool start()
	{
		bool res = true;
		for (SizeT i=0; i<mThreads.size(); i++)
			res &= mThreads[i]->start();
		return res;		
	}

	/**
	  * \brief Wait for all threads from that pool to exit
	  */
	bool joinAll()
	{
		bool res = true;
		for (SizeT i=0; i<mThreads.size(); i++)
			res &= mThreads[i]->join();
		return res;
	}

	/**
	  * \brief Wait for all the threads to exit, then removes all of them from
	  *        the pool
	  */
	void clear()
	{
		for (SizeT i=0; i<mThreads.size(); i++)
			delete mThreads[i];
		mThreads.clear();		
	}

	/**
	  * \brief Wait for all threads to exit then free all resources associated
	  *        with that pool
	  */
	~ThreadPool()
	{
		clear();
	}
};

#endif
